package com.qk.management.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.user.UserDo;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Just、倾城
 * @date 2025-10-07
 * @Description no
 * @Version 1.0
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";

    @Override
    public List<User> listByRole(String roleLabel) {
        //1.参数校验
        // 2.执行查询
        return userMapper.listByRoleLabel(roleLabel);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //1.参数教验合法性
        boolean hasNULL = BeanUtil.hasNullField(dto);
        if(hasNULL){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //2.根据用户名查询数据库获取用户对象
        User dbUser = userMapper.selectByUsername(dto.getUsername());

        //3.数据合法性校验
        if(ObjectUtils.isEmpty(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }

        //4.密码校验
        //4.1获取前端用户传递密码，对其进行MD5加密
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());//因为数据库中的密码也是使用MD5加密的
        String encodedPassword = dbUser.getPassword();
        //4.2进行密码对比
        boolean isChecked = ObjectUtil.equals(userPassword, encodedPassword);//使用hutool工具类进行密码对比
        if(!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        //5.数据封装返回
        //5.1 根据角色id查询角色标签 方式1 多表关联查询 方式2 根据角色id查询角色对象
        Role role = roleMapper.selectById(dbUser.getRoleId());
        //生成令牌需要携带用户信息
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtil.generateToken(claims))// TODO: token 未处理
                .build();
    }


    @Override
    public User getUserById(Integer id) {
        // 参数校验
        if(Objects.isNull(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return userMapper.selectById(id);
    }



    @Override
    public void deleteBatch(List<Integer> ids) {
        // 参数合法性校验
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if (!isNotEmpty) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 批量删除
        userMapper.deleteBatch(ids);
    }



    @Override
    public PageResult<UserDo> list(UserDTO dto) {
        // 参数校验（无）
        // 开始分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        //执行查询
        List<UserDo> list = userMapper.selectByPage(dto);

        //获取信息
        Page<UserDo> pageInfo = (Page<UserDo>) list;

        return PageResult.<UserDo>builder().total(Integer.getInteger(pageInfo.getTotal() + "")).rows(pageInfo.getResult()).build();
    }

    @Override
    public void add(User user) {
        // 参数校验 工具类处理 hutool 工具类
        boolean hasNULL = BeanUtil.hasNullField(user,"id","password","roleId","deptId","image","remark","updateTime","createTime");
        if(hasNULL){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 补全数据
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 设置默认密码
        // 原始密码
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString();
        // md5（message digest 消息摘要算法）加密的密码
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);

        // 插入
        userMapper.insert(user);
    }
}
